package com.ly.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @author 李岩
 * @date 2021/12/29-11:11
 * @describe
 */
@Configuration
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;

    @Bean
    PasswordEncoder passwordEncoder(){
        //不对密码进行加密(在springsecurity5中默认需要进行密码加密)
        return NoOpPasswordEncoder.getInstance();
    }
    //配置认证对象
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //在内存中定义，也可以在jdbc中去拿....
        /*auth.inMemoryAuthentication()
                .withUser("admin").password("123").roles("admin_manager")
                .and()
                .withUser("zhangsan").password("123").roles("admin_manager","prod_manager");*/
        auth.userDetailsService(userDetailsService);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        // 定制请求的授权规则, // 匹配许可，首页所有人可以访问  配置放行规则
        http.authorizeRequests().antMatchers("/images/**","/login.html","/css/**","/js/**","/src/**","/editor/**").permitAll();
        // 匹配拦截规则
        http.authorizeRequests().antMatchers("/role/**").hasRole("ADMIN");
        http.authorizeRequests().antMatchers("/menu/**").hasRole("PROD");
        http.authorizeRequests().antMatchers("/**").hasRole("LOGIN");


        // 开启自动配置的登录功能，如果没有权限，就会跳到登录页面！
        http.formLogin().loginPage("/login.html").loginProcessingUrl("/login");
        http.formLogin().defaultSuccessUrl("/admin/adminLogin").permitAll();
        http.csrf().disable();
        //允许使用内嵌框架 如iframe
        http.headers().frameOptions().sameOrigin();
        //配置登出界面
        http.logout().logoutUrl("/tuichu").clearAuthentication(true).invalidateHttpSession(true);
        http.logout().logoutSuccessUrl("/admin/logout").permitAll();
        //自定义无权限页面(无权限跳转到自定义403页面)
        http.exceptionHandling().accessDeniedPage("/403.html");

    }



}
